from django.shortcuts import render
from rest_framework.views import APIView
import random
import redis
from django.http import JsonResponse


class Phone(APIView):
    def get(self,request):
        phone = request.query_params.get('phone')
        print('.....................',phone)
        key ='sms_code_%s'%phone
        flag='flag_%s'%phone
        red = redis.Redis()
        if red.get(flag):
            return JsonResponse({'code':204,'err':'已经生成验证码'})
        else:
            # 生成短信验证码
            num=random.randint(1000,9999)
            red.set(flag,1,ex=60)
            red.set(key,num,ex=300)
            return JsonResponse({'code':200,'msg':'生成验证码成功','smsCode':num})
class Yz(APIView):
    def post(self,request):
        phone = request.data.get('phone')
        sms = request.data.get('smsCode')
        key = 'sms_code_%s' % phone
        red = redis.Redis()
        yzm = red.get(key)
        if yzm:
            if yzm.decode()==sms:
                red.close()
                return JsonResponse({'code':200,'msg':'验证码验证成功'})
            else:
                return JsonResponse({'code':204,'err':'验证失败'})
        else:
            return JsonResponse({'code':204,'msg':'验证失败'})

